package com.gg.utils.share

import android.app.Activity
import android.content.ComponentName
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Environment
import android.util.Log
import android.view.View
import java.text.SimpleDateFormat
import java.util.*
import android.net.Uri
import android.provider.MediaStore
import java.io.*
import android.graphics.Bitmap.CompressFormat
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Parcelable
import kotlin.collections.ArrayList
import android.support.v4.content.ContextCompat.startActivity
import android.support.v4.content.FileProvider


/**
 * Creator : GG
 * Date    : 2018/5/24
 * Mail    : gg.jin.yu@gmai.com
 * Explain :
 */
object CopyViewUtils {


    /**
     * 生成图片核心代码
     */
    fun generateBitmap(context: Context, view: View): Bitmap {
        view.isDrawingCacheEnabled = true
        //图片的宽度为屏幕宽度，高度为wrap_content
        view.measure(View.MeasureSpec.makeMeasureSpec(context.resources.displayMetrics.widthPixels, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
        //放置mView
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)
        view.buildDrawingCache()
        return view.drawingCache
    }

    fun noticeGallery(context: Context, filePath: String, name: String) {
        val values = ContentValues()
        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
        values.put(MediaStore.MediaColumns.DATA, filePath)
        context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.contentResolver, filePath, name, null)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }

        // 最后通知图库更新
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://$filePath")))
    }


    fun saveImageToGallery(context: Context, bmp: Bitmap): File {
        // 首先保存图片
        val appDir = File(Environment.getExternalStorageDirectory(), "QiYuan")
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        val fileName = System.currentTimeMillis().toString() + ".png"
        val file = File(appDir, fileName)
        try {
            val fos = FileOutputStream(file)
            bmp.compress(CompressFormat.PNG, 100, fos)
            fos.flush()
            fos.close()
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }

//         其次把文件插入到系统图库
//        try {
//            MediaStore.Images.Media.insertImage(context.contentResolver,
//                    file.absolutePath, fileName, null)
//        } catch (e: FileNotFoundException) {
//            e.printStackTrace()
//        }

        // Save the screenshot to the MediaStore
        val values = ContentValues()
        val resolver = context.contentResolver
        values.put(MediaStore.Images.ImageColumns.DATA, file.absolutePath)
        values.put(MediaStore.Images.ImageColumns.TITLE, fileName)
        values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName)
        values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/png")
        values.put(MediaStore.Images.ImageColumns.WIDTH, bmp.width)
        values.put(MediaStore.Images.ImageColumns.HEIGHT, bmp.height)
        val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)

        val out = resolver.openOutputStream(uri!!)
        bmp.compress(Bitmap.CompressFormat.PNG, 100, out)
        out!!.flush()
        out.close()

        // update file size in the database
        values.clear()
        values.put(MediaStore.Images.ImageColumns.SIZE, File(file.absolutePath).length())
        resolver.update(uri, values, null, null)
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://${file.absolutePath}")))
        return file
        // 最后通知图库更新
    }


    fun startShareImage(activity: Activity, list: ArrayList<Uri?>) {
        Log.w("uri=========", list.toString())
        //过滤出需要分享到对应的平台：微信好友、朋友圈、QQ好友。  可自行修改
        val targetApp = arrayOf("com.tencent.mm.ui.tools.ShareImgUI", "com.tencent.mm.ui.tools.ShareToTimeLineUI", "com.tencent.mobileqq.activity.JumpActivity")
        /** * 分享图片 */
//        val bitmap = getImageFromAssetsFile(activity, "img_share.jpg")  //从assets目录中取到对应的文件，文件名自行修改
//        val localImage = saveBitmap(bitmap!!, "share.jpg")    //分享前，需要先将图片存在本地（记得添加权限），文件名自行修改
        val shareIntent = Intent(Intent.ACTION_SEND_MULTIPLE)
        shareIntent.type = "image/*" //设置分享内容的类型：图片
        shareIntent.putExtra(Intent.EXTRA_STREAM, list)
        try {
            val resInfo = activity.packageManager.queryIntentActivities(shareIntent, 0)
            if (!resInfo.isEmpty()) {
                val targetedShareIntents = ArrayList<Intent>()
                for (info in resInfo) {
                    val targeted = Intent(Intent.ACTION_SEND_MULTIPLE)
                    targeted.type = "image/*"  //设置分享内容的类型
                    val activityInfo = info.activityInfo
                    //如果还需要分享至其它平台，可以打印出具体信息，然后找到对应的Activity名称，填入上面的数组中即可
//                  println("package = ${activityInfo.packageName}, activity = ${activityInfo.name}")

                    //进行过滤（只显示需要分享的平台）
//                    if (targetApp.any { it == activityInfo.name }) {
                        val comp = ComponentName(activityInfo.packageName, activityInfo.name)
                        targeted.component = comp
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            targeted.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
                        targeted.putExtra("Kdescription", "我分享成功啦！！！！！！")
                        targeted.putExtra(Intent.EXTRA_STREAM, list)
                        targetedShareIntents.add(targeted)
//                    }
                }
                val chooserIntent = Intent.createChooser(targetedShareIntents.removeAt(0), "选择要分享到的平台")
                if (chooserIntent != null) {
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toTypedArray<Parcelable>())
                    activity.startActivity(chooserIntent)
                }
            }
        } catch (e: Exception) {
            Log.e("------", "Unable to share image,  logs : " + e.toString())
        }
    }


}